home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 484 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: news.sprintlink.net!datalytics!news
  2. From: Rob Stewart <stew@datalytics.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Purpose of constructor initializer list?
  5. Date: 4 Jan 1996 17:36:36 GMT
  6. Organization: Datalytics, Inc
  7. Message-ID: <4ch374$ldg@gold.datalytics.com>
  8. References: <EMERICK.95Dec9130521@csa.bu.edu> <4brblp$h1r@news.puug.pt>
  9. NNTP-Posting-Host: pc071.datalytics.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 1.22 (Windows; I; 32bit)
  14.  
  15. In article <EMERICK.95Dec9130521@csa.bu.edu>
  16. emerick@csa.bu.edu (Emerick Rogul) writes:
  17.  
  18. > I'm confused about why and when one should use the constructor
  19. > initializer list.  I understand that when I derive a new class that's
  20. > how I initialize the base class.  But in many examples, it seems the
  21. > initializer list is used to initialize the derived class also.  Is
  22. > there any benefit to initializing the class in the initializer list
  23. > rather than simply in the constructor?  
  24.  
  25. The benefit is one of performance.  Without an initializer 
  26. list, the compiler will initialize all data members (dms) in 
  27. the class before invoking the c'tor body.  For objects, 
  28. default construction can be trivial or expensive.  After this 
  29. initialization, the c'tor body must assign values to these 
  30. dms, so you then invoke the assignment operator on objects.  
  31. For many classes, this can mean undoing what the default c'tor 
  32. did, then assigning the new value.
  33.  
  34. For built-in types, this is moot.  The compiler doesn't 
  35. initialize non-static variables.  But, since you never know 
  36. when a dm will change types (perhaps you've added a class to 
  37. handle the counter behavior and use that class in place of 
  38. size_t for a counter variable), and for consistency with all 
  39. other dms, you should initialize all dms.
  40.  
  41. > Is it an attempt to make the
  42. > constructor empty?
  43.  
  44. Using an initializer list, by definition, does not make for an 
  45. empty c'tor.  The initializer list is part of the c'tor's 
  46. code.
  47.  
  48. > Thanks,
  49. > Emerick Rogul
  50. > emerick@cs.bu.edu
  51.  
  52. -- 
  53. Robert Stewart        | My opinions are usually my own.
  54. Datalytics, Inc.
  55. (513)226-7700
  56. stew@datalytics.com
  57.  
  58.  
  59.